package com.example.ricebibackend.common.utils;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * redis常用工具类
 * @author ricejson
 */
@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    /**
     * 设置键值对
     * @param key 键
     * @param value 值
     * @return 是否插入成功
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil set:{},{}", key, value, e);
            return false;
        }
    }

    /**
     * 设置键值对（带过期时间）
     * @param key 键
     * @param value 值
     * @param expireTime 过期时间（秒）
     * @return 是否插入成功
     */
    public boolean set(String key, String value, Long expireTime) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil set:{},{},{}", key, value, expireTime, e);
            return false;
        }
    }

    /**
     * 获取值
     * @param key 键
     * @return 键对应的值
     */
    public String get(String key) {
        try {
            return StringUtils.hasText(key)
                    ? stringRedisTemplate.opsForValue().get(key)
                    : null;
        } catch (Exception e) {
            logger.error("RedisUtil get:{}", key, e);
            return null;
        }
    }

    /**
     * 删除键值对
     * @return 是否删除成功
     */
    public boolean del(String... key) {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                } else {
                    stringRedisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
                return true;
            }
        } catch (Exception e) {
            logger.error("RedisUtil del:{}", key, e);
            return false;
        }
        return false;
    }

    /**
     * 是否存在键
     * @param key 键
     * @return 是否存在键
     */
    public boolean exists(String key) {
        try {
            return stringRedisTemplate.hasKey(key);
        } catch (Exception e) {
            logger.error("RedisUtil exists:{}", key, e);
            return false;
        }
    }
}
